﻿using System.Web;

namespace AspNetInfo.Core
{
    public class EnvironmentPermissions
    {
        private static AspNetHostingPermissionLevel _trustLevel = AspNetHostingPermissionLevel.None;

        public AspNetHostingPermissionLevel TrustLevel
        {
            get
            {
                if (_trustLevel == AspNetHostingPermissionLevel.None)
                {
                    _trustLevel = GetCurrentTrustLevel();
                }
                return _trustLevel;
            }
        }


        // see http://blogs.msdn.com/dmitryr/archive/2007/01/23/finding-out-the-current-trust-level-in-asp-net.aspx
        private static AspNetHostingPermissionLevel GetCurrentTrustLevel()
        {
            foreach (AspNetHostingPermissionLevel trustLevel in
                    new AspNetHostingPermissionLevel[] {
                AspNetHostingPermissionLevel.Unrestricted,
                AspNetHostingPermissionLevel.High,
                AspNetHostingPermissionLevel.Medium,
                AspNetHostingPermissionLevel.Low,
                AspNetHostingPermissionLevel.Minimal 
            })
            {
                try
                {
                    new AspNetHostingPermission(trustLevel).Demand();
                }
                catch (System.Security.SecurityException)
                {
                    continue;
                }

                return trustLevel;
            }

            return AspNetHostingPermissionLevel.None;
        }
    }
}
